<?php
class FrontendAction extends PiscesAction
{
	public function __construct()
	{
		parent::__construct();
	}
	
	public function beforeExecute()
	{
		parent::beforeExecute();
		$this->data['site']['site_name'] = 'vtui';
		$this->viewDir			= $this->viewDir.$this->data['template'].'/';
		$this->getUserInfo();
		
		$this->data['categoryId'] = $this->context->get('c');
	}
	
	public function getSeoStr($str,$replace)
	{
		foreach($replace as $k=>$v)
		{
			$str	= str_replace('{'.$k.'}',$v,$str);
		}
		return $str;
	}
	
	public function error($code)
	{
		if($code==404)
		{
			$this->redirect($this->data['baseurl'].'404.html');
		}
	}
	
	//跳转到首页
	protected function goToHomePage()
	{
		$this->redirect($this->data['baseurl']);
	}
	
	private function getUserInfo()
	{
		$user = array();
		//优先用cookie中取登陆信息
		$cookie = C('LtCookie');
		$authCode 	= $cookie->getCookie('user_auth');
		if($authCode)
		{
			list($id, $username, $password, $expire) = explode("\t", $authCode);
			
			$userService	= new BaseDbService('user');
			$user			= $userService->get($id);
			if(!$user)
			{
				return false;
			}
			
			if($user['password']!=$password)
			{
				return false;
			}
			
			if ($user && $user['id'] == $id)
			{
				if(empty($user['logo']))
				{
					$user['logo']	= $this->data['baseurl'].'images/avatar-120.png';
				}
				$this->data['user']	= $user;
				//更新cookie
				if($expire-time()<600)
				{
					$expire		= time() + 1200;
					$authCode 	= $user['id'] . "\t" . $user['username']. "\t" .$user['password']. "\t" .$expire;
					$cookie->setCookie('user_auth', $authCode, $expire);
				}
			}
			else
			{
				$this->data['user'] = '';
				$cookie->delCookie('user_auth');
			}
		}
		
		return $user;
	}
	
}